<?php

namespace app\admin\controller\yunfood\shop;

use addons\yunfood\model\PrinterDevice;
use app\admin\model\Admin;
use app\admin\model\yunfood\Shop as ShopModel;
use addons\yunfood\library\Backend;

/**
 * 门店
 */
class Main extends Backend
{
    /**
     * @var ShopModel
     */
    protected $model;

    protected $shopField = 'id';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new ShopModel();

        // 打印机列表
        $this->view->assign('printerList', PrinterDevice::getOptionList());

        // 管理员列表
        $adminList = Admin::field(['id', 'nickname'])->select();
        $adminList = array_column($adminList, 'nickname', 'id');
        $this->view->assign('adminList', $adminList);

        // 状态
        $this->view->assign('statusList', $this->model::getStatusList());
        $this->assignconfig('statusList', $this->model::getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            // 转发到selectShop
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            // 重载查询条件
            $filter = $this->request->get('filter');
            $op = $this->request->get('op');
            list($filter, $op) = $this->formatFilterOp($filter, $op);
            $this->request->get(['filter' => $filter, 'op' => $op]);

            // 通用查询条件
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // 所属门店
            $where = $this->getShopWhere($where, 'id');
            $list = $this->model->where($where)->order($sort, $order)->limit($offset, $limit)->paginate($limit);
            $result = array(
                'total' => $list->total(),
                'rows'  => $list->items(),
            );

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 格式化查询条件
     *
     * @param $filter
     * @param $op
     * @return array
     */
    private function formatFilterOp($filter, $op)
    {
        $filter = json_decode($filter, true);
        $op = json_decode($op, true);

        return [json_encode($filter), json_encode($op)];
    }

    public function recyclebin()
    {
        return;
    }

    public function destroy($ids = null)
    {
        return;
    }

    public function restore($ids = null)
    {
        return;
    }
}
